package com.itheima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.article.dto.ArticleHomeDto;
import com.itheima.article.dto.ArticleInfoDto;
import com.itheima.article.mapper.ApArticleConfigMapper;
import com.itheima.article.mapper.ApArticleContentMapper;
import com.itheima.article.pojo.ApArticle;
import com.itheima.article.mapper.ApArticleMapper;
import com.itheima.article.pojo.ApArticleConfig;
import com.itheima.article.pojo.ApArticleContent;
import com.itheima.article.service.ApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.vo.PageResultVo;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.feign.WmNewsFeign;
import com.itheima.wemedia.pojo.WmNews;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version 1.0
 * @description <p>已发布的文章信息 业务实现</p>
 * @package com.itheima.article.service.impl
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleContentMapper articleContentMapper;

    @Autowired
    private ApArticleConfigMapper articleConfigMapper;

    @Autowired
    private WmNewsFeign wmNewsFeign;

    /**
     * 同步自媒体文章到文章微服务
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public boolean saveArticleInfo(ArticleInfoDto dto) {

        //保存文章表数据
        ApArticle apArticle = dto.getApArticle();
        Long id = apArticle.getId();
        if (null != id) {
            //id存在，代表着有旧文章，需要删除旧文章的相关表
            //删除文章表
            removeById(id);
            //删除文章内容表 (因为文章id与其他2个表id一致，所以可以使用其当主键删除)
            articleContentMapper.deleteById(id);
            //删除文章配置表
            articleConfigMapper.deleteById(id);
            //设置id为null
            apArticle.setId(null);
        }
        save(apArticle);
        //保存文章内容表数据
        ApArticleContent apArticleContent = dto.getApArticleContent();
        apArticleContent.setId(apArticle.getId());
        apArticleContent.setArticleId(apArticle.getId());
        articleContentMapper.insert(apArticleContent);
        //保存文章配置表数据
        ApArticleConfig apArticleConfig = dto.getApArticleConfig();
        apArticleConfig.setId(apArticle.getId());
        apArticleConfig.setArticleId(apArticle.getId());
        articleConfigMapper.insert(apArticleConfig);
        //远程调用自媒体微服务更新文章状态和文章微服务的文章id  article_id
        WmNews wmNews = new WmNews();
        wmNews.setId(dto.getWmNewsId());
        wmNews.setArticleId(apArticle.getId());
        wmNews.setStatus(BusinessConstants.WmNewsConstants.STATUS_PUBLISHED);
        wmNews.setEnable(BusinessConstants.WmNewsConstants.ENABLE_ON);
        ResultVo updateResult = wmNewsFeign.update(wmNews);
        if (!updateResult.isSuccess()) {
            throw new LeadNewsException("远程调用自媒体同步文章状态失败");
        }
        return true;
    }

    /**
     * app端文章分页查询
     *
     * @param dto
     * @param loadType
     * @return
     */
    @Override
    public PageResultVo<ApArticle> pageList(ArticleHomeDto dto, int loadType) {
        //校验参数
        dto.checkSize();
        //如果前端传来的参数里maxBehotTime和minBehotTime没值，我们要在这里给它赋值
        if (null == dto.getMaxBehotTime()) {
            dto.setMaxBehotTime(new Date());
        }
        if (null == dto.getMinBehotTime()) {
            dto.setMinBehotTime(new Date());
        }
        //构建分页参数
        IPage<ApArticle> pageInfo = new Page<>(dto.getLoaddir(), dto.getSize());
        //查询
        List<ApArticle> list = getBaseMapper().pageList(pageInfo, dto, loadType);


        return PageResultVo.pageResult(dto.getLoaddir(), dto.getSize(), pageInfo.getTotal(), list);
    }

    /**
     * 查询文章信息详情
     *
     * @param map
     * @return
     */
    @Override
    public Map<String, Object> loadArticleInfo(Map<String, String> map) {
        String resultArticleId = map.get("articleId");
        Long articleId = Long.valueOf(resultArticleId);
        //先查询文章配置信息表，如果已经下架或者已经删除的文章不要
        LambdaQueryWrapper<ApArticleConfig> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ApArticleConfig::getIsDown, BusinessConstants.ArticleConfig.IS_DOWN_NO);
        lqw.eq(ApArticleConfig::getIsDelete, BusinessConstants.ArticleConfig.IS_DELETE_NO);
        lqw.eq(ApArticleConfig::getId, articleId);
        ApArticleConfig articleConfig = articleConfigMapper.selectOne(lqw);
        //如果查询到的文章配置表内容为空，就报错
        if (null == articleConfig) {
            throw new LeadNewsException("文章已下架或已删除");
        }
        //文章配置表内容不为空，在查询文章内容表
        ApArticleContent articleContent = articleContentMapper.selectById(articleId);
        //构建Map<String, Object>，返回
        Map<String, Object> resultMap =new HashMap<>();
        resultMap.put("config",articleConfig);
        resultMap.put("content",articleContent);
        return resultMap;
    }
}
